/*
 * Copyright (c) 2011-2023, ThinkWide (cnet2001@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.thinkwide.data.ormapping.conditions;

import com.thinkwide.data.ormapping.conditions.fragment.MFOrderByFragment;
import com.thinkwide.data.ormapping.conditions.fragment.MFGroupByFragment;
import com.thinkwide.data.ormapping.conditions.fragment.MFHavingFragment;
import com.thinkwide.data.ormapping.conditions.fragment.MFSqlFragments;
import com.thinkwide.data.ormapping.sql.MFSqlBase;
import lombok.Data;

import java.util.Arrays;

import static java.util.stream.Collectors.joining;

/**
 * TODO
 *
 * @author andyzhang
 * @since 2023/06/15
 */
@Data
public abstract class AbstractWrapper<T, R, Children extends AbstractWrapper<T, R, Children>> {

    protected final Children self = (Children) this;

    private MFSqlFragments sqlFragments = new MFSqlFragments();

    public Children select(R... columns){
        return select(true, columns);
    }

    public Children select(boolean condition,  R... columns){
        if (condition){
            for(R column:columns){
                sqlFragments.getGroupByList().add(new MFGroupByFragment(columnToString(column)));
            }
        }
        return self;
    }

    public Children groupBy(boolean condition,  R... columns) {
        if (condition){
            for(R column:columns){
                sqlFragments.getGroupByList().add(new MFGroupByFragment(columnToString(column)));
            }
        }
        return self;
    }

    public Children orderBy(boolean condition, boolean isAsc,R... columns) {
        if (condition){
            for(R column:columns){
                sqlFragments.getOrderByList().add(new MFOrderByFragment(columnToString(column),isAsc));
            }
        }
        return self;
    }

    public Children having(boolean condition, String... sqlHaving) {
        if (condition){
            for(String param:sqlHaving){
                sqlFragments.getHavingList().add(new MFHavingFragment(param));
            }
        }
        return self;
    }

    protected String columnToString(R column) {
        return (String) column;
    }

    /**
     * 多字段转换为逗号 "," 分割字符串
     *
     * @param columns 多字段
     */
    protected String columnsToString(R... columns) {
        return Arrays.stream(columns).map(this::columnToString).collect(joining(MFSqlBase.COMMA));
    }
}
